package org.lex.utils.text;

public class SizeFormat {
	// e.g.: 1024: SHORT-> 1K, FULL -> 1 Kilo
	public enum Style {
		LOWCASE_SHORT, LOWCASE_FULL, UPCASE_SHORT, UPCASE_FULL
	}

	public static final SizeFormat.Style DEFAULT_STYLE = SizeFormat.Style.UPCASE_SHORT;

	public static String autoFormat(long size) {
		return SizeFormat.autoFormat(size, SizeFormat.DEFAULT_STYLE).toString();
	}

	public static String autoFormat(long size, SizeFormat.Style style) {
		return SizeFormat.autoFormat(new StringBuilder(), size, style).toString();
	}

	public static StringBuilder autoFormat(StringBuilder dest, long size, SizeFormat.Style style) {
		SizeUnit unit = findProperSizeUnit(size);
		return SizeFormat.format(dest, size, unit, style, unit.bits);
	}

	public static StringBuilder autoFormat(StringBuilder dest, long size, SizeFormat.Style style, int maxFractionDigits) {
		SizeUnit unit = findProperSizeUnit(size);
		return SizeFormat.format(dest, size, unit, style, maxFractionDigits);
	}

	private static SizeUnit findProperSizeUnit(long size) {
		SizeUnit unit = null;
		if (size < SizeUnit.K.value)
			unit = SizeUnit.One;
		else if (size < SizeUnit.M.value)
			unit = SizeUnit.K;
		else if (size < SizeUnit.G.value)
			unit = SizeUnit.M;
		else if (size < SizeUnit.T.value)
			unit = SizeUnit.G;
		else if (size < SizeUnit.P.value)
			unit = SizeUnit.T;
		else if (size < SizeUnit.E.value)
			unit = SizeUnit.P;
		else
			unit = SizeUnit.E;
		return unit;
	}

	public static String format(long size, SizeUnit unit) {
		return format(size, unit, SizeFormat.DEFAULT_STYLE);
	}

	public static String format(long size, SizeUnit unit, SizeFormat.Style style) {
		return format(size, unit, style, unit.bits);
	}

	public static String format(long size, SizeUnit unit, int maximumFractionDigits) {
		return format(size, unit, SizeFormat.DEFAULT_STYLE, maximumFractionDigits);
	}

	public static String format(long size, SizeUnit unit, SizeFormat.Style style, int maximumFractionDigits) {
		return format(new StringBuilder(), size, unit, style, maximumFractionDigits).toString();
	}

	/**
	 * @param dest
	 * @param size
	 * @param unit
	 * @param style
	 *            ��λ
	 * @param maximumFractionDigits
	 *            С�����󳤶�
	 * @return
	 */
	public static StringBuilder format(StringBuilder dest, long size, SizeUnit unit, SizeFormat.Style style, int maximumFractionDigits) {
		if (null == dest)
			dest = new StringBuilder();
		long value = unit.value;
		long integer = size / value;
		dest.append(integer);
		long fraction = size % value;
		if (0 != fraction) {
			dest.append('.');
			PadUtilities.pad(Long.toString(fraction), dest, true, 0, maximumFractionDigits);
		}
		dest.append(' ');
		dest.append(unit.getStyle(style));
		return dest;
	}
}
